<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="视频标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入视频标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="拍摄地点" prop="location">-->
<!--        <el-input-->
<!--          v-model="queryParams.location"-->
<!--          placeholder="请输入拍摄地点"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.spff_video_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

          <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-check"
            size="mini"
            :disabled="multiple"
            @click="handleBatchApprove"
            v-hasPermi="['system:videos:edit']"
          >批量通过</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-close"
            size="mini"
            :disabled="multiple"
            @click="handleBatchReject"
            v-hasPermi="['system:videos:edit']"
          >批量拒绝</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:videos:edit']"
          >修改状态</el-button>
        </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:videos:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:videos:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="作者" align="center" prop="nickname" width="80" />
      <el-table-column label="视频标题" align="center" prop="title" width="150" />
      <el-table-column label="视频描述" align="center" prop="description" width="200" />
      <el-table-column label="视频预览" align="center" prop="videoUrl" width="180">
        <template slot-scope="scope">
          <div class="video-thumb-wrapper" @mouseenter="handleThumbHover(scope.row, true)" @mouseleave="handleThumbHover(scope.row, false)">
            <div class="video-thumb">
              <img v-if="scope.row.coverUrl" :src="scope.row.coverUrl" alt="封面" class="thumb-image" @click="playVideoPreview(scope.row)" />
              <div v-else class="thumb-placeholder">
                <i class="el-icon-picture-outline"></i>
              </div>
              <div class="video-overlay" :class="{ 'show': scope.row._showOverlay }">
                <i class="el-icon-video-play play-icon" @click="playVideoPreview(scope.row)"></i>
                <div class="video-info">
                  <span class="duration-badge">{{ formatDuration(scope.row.duration) }}</span>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tags" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.tags" class="video-tags">
            <el-tag v-for="(tag, index) in (scope.row.tags ? scope.row.tags.split(',').slice(0, 2) : [])"
                    :key="index"
                    size="mini"
                    type="info"
                    class="tag-item">
              {{ tag.trim() }}
            </el-tag>
          </span>
          <span v-else class="no-data">-</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryName" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.categoryName" size="small" class="category-tag">
            <i class="el-icon-folder-opened"></i> {{ scope.row.categoryName }}
          </el-tag>
          <span v-else class="no-data">-</span>
        </template>
      </el-table-column>
      <el-table-column label="拍摄地点" align="center" prop="location" width="130" />
      <el-table-column label="是否私密" align="center" prop="isPrivate" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.spff_video_private" :value="scope.row.isPrivate"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.spff_video_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="" align="center" prop="updatedAt" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.status == 2"
                  size="mini"
                  type="success"
                  icon="el-icon-check"
                  @click="handleQuickApprove(scope.row)"
                  v-hasPermi="['system:videos:edit']"
                >通过</el-button>
                <el-button
                  v-if="scope.row.status == 2"
                  size="mini"
                  type="danger"
                  icon="el-icon-close"
                  @click="handleQuickReject(scope.row)"
                  v-hasPermi="['system:videos:edit']"
                >拒绝</el-button>
<!--                <el-button-->
<!--                  size="mini"-->
<!--                  type="primary"-->
<!--                  icon="el-icon-edit"-->
<!--                  @click="handleUpdate(scope.row)"-->
<!--                  v-hasPermi="['system:videos:edit']"-->
<!--                >修改</el-button>-->
                <el-button
                  size="mini"
                  type="info"
                  icon="el-icon-view"
                  @click="handleView(scope.row)"
                  v-hasPermi="['system:videos:query']"
                >查看</el-button>
              </template>
            </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 视频审核详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="作者ID" prop="userId">-->
<!--          <el-input v-model="form.userId" placeholder="请输入作者ID" />-->
<!--        </el-form-item>-->
        <el-form-item label="作者" prop="nickname">
          <el-input v-model="form.nickname" readonly />
        </el-form-item>
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="form.title" readonly />
        </el-form-item>
        <el-form-item label="视频描述" prop="description">
          <el-input v-model="form.description" type="textarea" readonly :rows="3" />
        </el-form-item>
        <el-form-item label="视频：" prop="videoUrl">
          <!-- 视频预览 -->
          <div v-if="form.videoUrl" style="margin-top: 10px;">
            <div style="margin-bottom: 5px; font-size: 14px; color: #606266;">视频预览：</div>
            <video
              :src="form.videoUrl"
              :poster="form.coverUrl"
              controls
              preload="metadata"
              style="width: 100%; max-width: 400px; height: 250px; object-fit: cover; border-radius: 4px; border: 1px solid #dcdfe6;"
              @loadedmetadata="updateFormDuration($event)"
            >
              您的浏览器不支持视频播放
            </video>
            <div style="font-size: 12px; color: #909399; margin-top: 5px;">
              时长: {{ formatDuration(form.duration) }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="视频封面" prop="coverUrl">
          <image-upload v-model="form.coverUrl" :disabled="true"/>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" type="textarea" readonly :rows="2" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryName">
          <el-input v-model="form.categoryName" readonly />
        </el-form-item>
        <el-form-item label="拍摄地点" prop="location">
          <el-input v-model="form.location" readonly />
        </el-form-item>
        <el-form-item label="是否私密" prop="isPrivate">
          <el-select v-model="form.isPrivate" disabled>
            <el-option
              v-for="dict in dict.type.spff_video_private"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" :disabled="!isEdit">
            <el-option
              v-for="dict in dict.type.spff_video_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isEdit && form.status == 2" type="success" icon="el-icon-check" @click="quickApprove">审核通过</el-button>
        <el-button v-if="isEdit && form.status == 2" type="danger" icon="el-icon-close" @click="quickReject">审核拒绝</el-button>
        <el-button v-if="isEdit" type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVideos, getVideos, delVideos, addVideos, updateVideos } from "@/api/system/videos"

export default {
  name: "VideoReview",
  dicts: ['spff_video_private', 'spff_video_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频表格数据
      videosList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        location: null,
        status: 2, // 默认显示待审核状态的视频
      },
      // 表单参数
      form: {},
      // 是否编辑模式
      isEdit: false,
      // 表单校验
      rules: {
        status: [
          { required: true, message: "请选择审核状态", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询视频列表 */
    getList() {
      this.loading = true
      listVideos(this.queryParams).then(response => {
        this.videosList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        title: null,
        description: null,
        videoUrl: null,
        coverUrl: null,
        duration: null,
        width: null,
        height: null,
        format: null,
        size: null,
        tags: null,
        categoryId: null,
        location: null,
        latitude: null,
        longitude: null,
        viewCount: null,
        likeCount: null,
        commentCount: null,
        shareCount: null,
        collectCount: null,
        isPrivate: null,
        status: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加视频"
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset()
      this.isEdit = false
      const id = row ? row.id : this.ids
      getVideos(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "视频详情"
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.isEdit = true
      const id = row ? row.id : this.ids
      getVideos(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改视频状态"
      })
    },
    /** 批量批准操作 */
    handleBatchApprove() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要批准的视频")
        return
      }
      this.$modal.confirm('确认批准选中的视频吗？').then(() => {
        this.batchUpdateStatus(this.ids, 1, "批准")
      })
    },
    /** 批量拒绝操作 */
    handleBatchReject() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要拒绝的视频")
        return
      }
      this.$modal.confirm('确认拒绝选中的视频吗？').then(() => {
        this.batchUpdateStatus(this.ids, 0, "拒绝")
      })
    },
    /** 快速批准单个视频 */
    handleQuickApprove(row) {
      this.$modal.confirm(`确认批准视频"${row.title}"吗？`).then(() => {
        this.updateVideoStatus(row.id, 1, "批准")
      })
    },
    /** 快速拒绝单个视频 */
    handleQuickReject(row) {
      this.$modal.confirm(`确认拒绝视频"${row.title}"吗？`).then(() => {
        this.updateVideoStatus(row.id, 0, "拒绝")
      })
    },
    /** 对话框中的快速批准 */
    quickApprove() {
      this.$modal.confirm('确认批准此视频吗？').then(() => {
        this.updateVideoStatus(this.form.id, 1, "批准")
        this.open = false
      })
    },
    /** 对话框中的快速拒绝 */
    quickReject() {
      this.$modal.confirm('确认拒绝此视频吗？').then(() => {
        this.updateVideoStatus(this.form.id, 0, "拒绝")
        this.open = false
      })
    },
    /** 更新单个视频状态 */
    updateVideoStatus(id, status, action) {
      const updateData = { id: id, status: status }
      updateVideos(updateData).then(response => {
        this.$modal.msgSuccess(`${action}成功`)
        this.getList()
      }).catch(() => {
        this.$modal.msgError(`${action}失败`)
      })
    },
    /** 批量更新视频状态 */
    batchUpdateStatus(ids, status, action) {
      const promises = ids.map(id => {
        const updateData = { id: id, status: status }
        return updateVideos(updateData)
      })

      Promise.all(promises).then(() => {
        this.$modal.msgSuccess(`批量${action}成功`)
        this.getList()
      }).catch(() => {
        this.$modal.msgError(`批量${action}失败`)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVideos(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除视频编号为"' + ids + '"的数据项？').then(function() {
        return delVideos(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/videos/export', {
        ...this.queryParams
      }, `videos_${new Date().getTime()}.xlsx`)
    },
    /** 格式化视频时长 */
    formatDuration(duration) {
      if (!duration) return '未知'
      const minutes = Math.floor(duration / 60)
      const seconds = Math.floor(duration % 60)
      return `${minutes}:${seconds.toString().padStart(2, '0')}`
    },
    /** 更新视频时长 */
    updateDuration(row, event) {
      if (!row.duration && event.target.duration) {
        row.duration = Math.floor(event.target.duration)
      }
    },
    /** 更新表单中的视频时长 */
    updateFormDuration(event) {
      if (!this.form.duration && event.target.duration) {
        this.form.duration = Math.floor(event.target.duration)
      }
    },
    /** 播放视频预览 */
    playVideoPreview(row) {
      // 打开视频详情对话框
      this.handleView(row)
    },
    /** 处理缩略图hover */
    handleThumbHover(row, show) {
      this.$set(row, '_showOverlay', show)
    },
    /** 格式化数字 */
    formatCount(count) {
      if (!count) return '0'
      if (count >= 10000) {
        return (count / 10000).toFixed(1) + 'w'
      }
      if (count >= 1000) {
        return (count / 1000).toFixed(1) + 'k'
      }
      return count.toString()
    }
  }
}
</script>

<style lang="scss" scoped>
/* 视频配色主题 */
$bg-color: #F8F9FA;
$text-primary: #2C3E50;
$text-secondary: #95A5A6;
$interact-red: #E74C3C;
$interact-blue: #3498DB;
$success-color: #27ae60;
$warning-color: #E67E22;
$category-color: #F39C12;
$overlay-bg: rgba(0, 0, 0, 0.4);

/* 容器背景 */
.app-container {
  background: $bg-color;
  color: $text-primary;
}

/* 视频缩略图容器 */
.video-thumb-wrapper {
  display: inline-block;
  position: relative;
  cursor: pointer;

  .video-thumb {
    position: relative;
    width: 140px;
    height: 85px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .thumb-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .thumb-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      color: $text-secondary;
      font-size: 32px;
    }

    .video-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: $overlay-bg;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s ease;

      &.show {
        opacity: 1;
      }

      .play-icon {
        font-size: 36px;
        color: #fff;
        margin-bottom: 8px;
        transition: transform 0.2s ease;
        cursor: pointer;

        &:hover {
          transform: scale(1.2);
        }
      }

      .video-info {
        .duration-badge {
          background: rgba(255, 255, 255, 0.9);
          color: $text-primary;
          padding: 3px 8px;
          border-radius: 4px;
          font-size: 11px;
          font-weight: 600;
        }
      }
    }
  }
}

/* 标签样式 */
.video-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;

  .tag-item {
    background: #ecf5ff;
    border-color: #b3d8ff;
    color: $interact-blue;
    font-size: 12px;
  }
}

.category-tag {
  background: #fef5e7;
  border-color: $category-color;
  color: $category-color;
  font-weight: 500;

  i {
    margin-right: 3px;
  }
}

/* 无数据占位 */
.no-data {
  color: $text-secondary;
  font-size: 12px;
}

/* 表格样式优化 */
::v-deep .el-table {
  background: #fff;

  th {
    background: #fafbfc !important;
    color: $text-primary;
    font-weight: 600;
  }

  tr {
    transition: background 0.2s ease;

    &:hover {
      background: #f8f9fa !important;
    }
  }

  .cell .el-tag {
    margin: 2px;
  }
}

/* 按钮样式优化 */
::v-deep .el-button {
  transition: all 0.3s ease;

  + .el-button {
    margin-left: 5px;
  }

  &.el-button--primary {
    background: $interact-blue;
    border-color: $interact-blue;

    &:hover {
      background: darken($interact-blue, 8%);
      border-color: darken($interact-blue, 8%);
    }
  }

  &.el-button--success {
    background: $success-color;
    border-color: $success-color;

    &:hover {
      background: darken($success-color, 8%);
      border-color: darken($success-color, 8%);
    }
  }

  &.el-button--danger {
    background: $interact-red;
    border-color: $interact-red;

    &:hover {
      background: darken($interact-red, 8%);
      border-color: darken($interact-red, 8%);
    }
  }

  &.el-button--warning {
    background: $warning-color;
    border-color: $warning-color;
    color: #fff;

    &:hover {
      background: darken($warning-color, 8%);
      border-color: darken($warning-color, 8%);
    }
  }

  &.el-button--info {
    background: $text-secondary;
    border-color: $text-secondary;
    color: #fff;

    &:hover {
      background: darken($text-secondary, 8%);
      border-color: darken($text-secondary, 8%);
    }
  }
}

/* 状态标签样式 */
::v-deep .el-tag {
  &.el-tag--success {
    background-color: rgba(39, 174, 96, 0.1);
    border-color: $success-color;
    color: $success-color;
  }

  &.el-tag--danger {
    background-color: rgba(231, 76, 60, 0.1);
    border-color: $interact-red;
    color: $interact-red;
  }

  &.el-tag--warning {
    background-color: rgba(230, 126, 34, 0.1);
    border-color: $warning-color;
    color: $warning-color;
  }
}

/* 对话框优化 */
::v-deep .el-dialog {
  border-radius: 8px;
  overflow: hidden;

  .el-dialog__header {
    background: #fafbfc;
    border-bottom: 1px solid #ebeef5;
    padding: 16px 20px;
  }

  .el-dialog__title {
    color: $text-primary;
    font-weight: 600;
    font-size: 16px;
  }

  .el-dialog__body {
    padding: 24px 20px;
  }

  .el-form-item__label {
    color: $text-primary;
    font-weight: 500;
  }
}

/* 视频预览样式 */
::v-deep video {
  border: 2px solid #e4e7ed;
  transition: border-color 0.3s ease;
  background: #000;

  &:hover {
    border-color: $interact-blue;
  }
}

/* 表单只读字段 */
::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner,
::v-deep .el-select.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: $text-primary;
  cursor: not-allowed;
}

/* 搜索表单优化 */
::v-deep .el-form--inline .el-form-item {
  margin-bottom: 12px;
}
</style>
